package com.mi.patient;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class patient2 {
//spark实现
//    val spark = SparkSession.builder().appName("MedicalInsurance").master("local").getOrCreate()
//    val data = spark.read
//            .option("header", "true")
//            .csv("data/data.csv")
//
//    val declaredExpenseDF = data
//            .select("药品费申报金额_SUM", "检查费申报金额_SUM", "治疗费申报金额_SUM", "手术费申报金额_SUM", "床位费申报金额_SUM", "成分输血申报金额_SUM", "一次性医用材料申报金额_SUM", "其它申报金额_SUM")
//            .rdd
//      .map(x => (x(0).toString.toFloat, x(1).toString.toFloat, x(2).toString.toFloat, x(3).toString.toFloat, x(4).toString.toFloat, x(5).toString.toFloat, x(6).toString.toFloat, x(7).toString.toFloat))
//
//
//    // 平均申报金额中，各项的占比
//    val declaredExpenseSum = declaredExpenseDF.reduce((a, b) => (a._1+b._1, a._2+b._2, a._3+b._3, a._4+b._4, a._5+b._5, a._6+b._6, a._7+b._7, a._8+b._8))
//    val declaredExpenseSumAmount = declaredExpenseSum._1 + declaredExpenseSum._2 + declaredExpenseSum._3 + declaredExpenseSum._4 + declaredExpenseSum._5 + declaredExpenseSum._6 + declaredExpenseSum._7 + declaredExpenseSum._8
//    println("平均药品费申报金额占比: " + declaredExpenseSum._1 / declaredExpenseSumAmount)
//    println("平均检查费申报金额占比: " + declaredExpenseSum._2 / declaredExpenseSumAmount)
//    println("平均治疗费申报金额占比: " + declaredExpenseSum._3 / declaredExpenseSumAmount)
//    println("平均手术费申报金额占比: " + declaredExpenseSum._4 / declaredExpenseSumAmount)
//    println("平均床位费申报金额占比: " + declaredExpenseSum._5 / declaredExpenseSumAmount)
//    println("平均成分输血申报金额占比: " + declaredExpenseSum._6 / declaredExpenseSumAmount)
//    println("平均一次性医用材料申报金额占比: " + declaredExpenseSum._7 / declaredExpenseSumAmount)
//    println("平均其它申报金额占比: " + declaredExpenseSum._8 / declaredExpenseSumAmount)
//
//    spark.stop()

    //mapreduce实现
    public static class patientMapper extends Mapper<LongWritable, Text, Text, FloatWritable> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, FloatWritable>.Context context) throws IOException, InterruptedException {
            if (key.get() == 0) return;
            String line = value.toString();
            String[] fields = line.split(",");
            // 药品费申报金额
            String drugDeclaredExpense = fields[32];
            // 检查费申报金额
            String checkDeclaredExpense = fields[38];
            // 治疗费申报金额
            String treatmentDeclaredExpense = fields[42];
            // 手术费申报金额
            String surgeryDeclaredExpense = fields[45];
            // 床位费申报金额
            String bedDeclaredExpense = fields[47];
            // 成分输血申报金额
            String bloodDeclaredExpense = fields[51];
            // 一次性医用材料申报金额
            String medicalDeclaredExpense = fields[54];
            // 其它申报金额
            String otherDeclaredExpense = fields[53];
            // 输出
            context.write(new Text("药品费申报金额"), new FloatWritable(Float.parseFloat(drugDeclaredExpense)));
            context.write(new Text("检查费申报金额"), new FloatWritable(Float.parseFloat(checkDeclaredExpense)));
            context.write(new Text("治疗费申报金额"), new FloatWritable(Float.parseFloat(treatmentDeclaredExpense)));
            context.write(new Text("手术费申报金额"), new FloatWritable(Float.parseFloat(surgeryDeclaredExpense)));
            context.write(new Text("床位费申报金额"), new FloatWritable(Float.parseFloat(bedDeclaredExpense)));
            context.write(new Text("成分输血申报金额"), new FloatWritable(Float.parseFloat(bloodDeclaredExpense)));
            context.write(new Text("一次性医用材料申报金额"), new FloatWritable(Float.parseFloat(medicalDeclaredExpense)));
            context.write(new Text("其它申报金额"), new FloatWritable(Float.parseFloat(otherDeclaredExpense)));
            }
    }

    public static class patientReducer extends Reducer<Text, FloatWritable, Text, FloatWritable> {
        private Map<String, Float> avgAmounts = new HashMap<>();
        private float avgAmountsSum;

        @Override
        protected void reduce(Text key, Iterable<FloatWritable> values, Reducer<Text, FloatWritable, Text, FloatWritable>.Context context) throws IOException, InterruptedException {
            float sum = 0;
            int count = 0;
            for (FloatWritable val : values) {
                sum += val.get();
                count++;
            }
            float average = sum / count;
            avgAmounts.put(key.toString(), average);
            avgAmountsSum += average;
        }

        @Override
        protected void cleanup(Reducer<Text, FloatWritable, Text, FloatWritable>.Context context) throws IOException, InterruptedException {
            ArrayList<Map.Entry<String, Float>> list = new ArrayList<>(avgAmounts.entrySet());
            list.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
            for(Map.Entry<String, Float> amount:list){
                context.write(new Text("平均" + amount.getKey() + "占比"), new FloatWritable(amount.getValue() / avgAmountsSum));
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        // 创建配置类
        Configuration config = new Configuration();
        // 创建Job作业对象
        Job job = Job.getInstance(config);
        // 指定Job对象所属的类
        job.setJarByClass(patient2.class);
        // 指定Mapper
        job.setMapperClass(patientMapper.class);
        // 指定Mapper输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(FloatWritable.class);
        // 指定Reducer
        job.setReducerClass(patientReducer.class);
        // 指定Reducer输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(FloatWritable.class);
        FileInputFormat.setInputPaths(job, new Path("data/data.csv"));
        // 指定处理结果的输出路径
        Path outputPath = new Path("output");
        FileSystem fs = FileSystem.get(config);
        if (fs.exists(outputPath)) {
            fs.delete(outputPath, true);
        }
        FileOutputFormat.setOutputPath(job, outputPath);
        // 提交作业
        boolean success = job.waitForCompletion(true);
        if (success) {
            System.out.println("执行成功");
        } else {
            System.out.println("执行失败");
        }
    }

}
